package com.uphone.kingmall.activity.personal.set;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.china.zhuoyue.BuildConfig;
import com.china.zhuoyue.R;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.bean.UserInfosBean;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.listener.onUploadFileListener;
import com.uphone.kingmall.utils.CaptureFileUtils;
import com.uphone.kingmall.utils.GlideCircleTransform;
import com.uphone.kingmall.utils.GlideUtils;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.PermissionsUtils;
import com.uphone.kingmall.utils.SharedPreferencesHelper;
import com.uphone.kingmall.view.dialog.OnDialogViewClickListener;
import com.uphone.kingmall.view.dialog.RadishDialog;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * <pre>
 *     author : 王雨
 *     e-mail : sunzengyan@outlook.com
 *     time   : 2018/07/31
 *     desc   :个人资料
 *     version: 1.0
 * </pre>
 */
public class PersonalDataActivity extends BaseActivity {
    private static final int MENBER_NAME = 100;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_icon)
    ImageView ivIcon;
    @BindView(R.id.rl_personal_set)
    RelativeLayout rlPersonalSet;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.rl_personal_sex)
    RelativeLayout rlPersonalSex;
    @BindView(R.id.tv_member_name)
    TextView tvMemberName;
    @BindView(R.id.rl_member_name)
    RelativeLayout rlMemberName;
    private UserInfosBean.UserInfoBean user;
    private int mItem;

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }

    private void loadData() {

        OkGoUtils.normalRequest(MyUrl.getUserInfo, null, new onNormalRequestListener() {
            @Override
            public void onSuccess(String response, int code) {
                if (code == 0) {
                    UserInfosBean bean = GsonUtils.getGson().fromJson(response, UserInfosBean.class);
                    user = bean.getUserInfo();
                    if (user != null) {
                        tvMemberName.setText("" + user.getUserName());
                        tvSex.setText("" + (user.getUserSex() == 1 ? "男" : "女"));
                        GlideUtils.getInstance().loadCircleImage(PersonalDataActivity.this, user.getUserPhoto(), ivIcon);
                        SharedPreferencesHelper.saveUserName(user.getUserName());
                        SharedPreferencesHelper.saveUserPhone(user.getUserMobile());
                        SharedPreferencesHelper.saveUserId(user.getUserId() + "");
                        SharedPreferencesHelper.saveUserImg(user.getUserPhoto());
                        SharedPreferencesHelper.saveUserInviteCode(user.getInviteCode() + "");
                    } else {
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_activity_personal_data;
    }

    @Override
    public void initView() {
        setStatusBar();
    }

    @Override
    public void initData() {

    }


    @OnClick({R.id.iv_back, R.id.rl_personal_set, R.id.rl_personal_sex, R.id.rl_member_name})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.rl_personal_set:
                // 修改头像
                showDialog();
                break;
            case R.id.rl_personal_sex:
                showDialogSex();
                break;
            case R.id.rl_member_name:
                startActivityForResult(new Intent(this, MemberNameActivity.class), MENBER_NAME);
                break;
        }
    }

    private void showDialogSex() {
        View view = View.inflate(this, R.layout.kingmall_dialog_selector, null);
        final TextView dialog_item1 = view.findViewById(R.id.dialog_item1);
        final TextView dialog_item2 = view.findViewById(R.id.dialog_item2);
        if (user != null && user.getUserSex() == 0) {
            // 女孩
            dialog_item1.setSelected(true);
            dialog_item2.setSelected(false);
        } else {
            dialog_item1.setSelected(false);
            dialog_item2.setSelected(true);
        }
        new RadishDialog.Builder(this).setView(view)
                .setClick(R.id.dialog_item1, new OnDialogViewClickListener() {
                    @Override
                    public void onClick(final RadishDialog dialog, View view) {
                        //修改性别
                        dialog_item1.setSelected(false);
                        dialog_item2.setSelected(true);
                        String userSex = "1";
                        HttpParams params = new HttpParams();
                        params.put("userSex", userSex);
                        OkGoUtils.progressRequest(MyUrl.editUserSex, PersonalDataActivity.this, params, new onNormalRequestListener() {
                            @Override
                            public void onSuccess(String body, int code) {
                                if (code == 0) {
                                    ToastUtils.showShort("设置成功");
                                    loadData();
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {

                            }
                        });
                        dialog.dismiss();
                    }
                })
                .setClick(R.id.dialog_item2, new OnDialogViewClickListener() {
                    @Override
                    public void onClick(RadishDialog dialog, View view) {
                        //修改性别
                        dialog_item1.setSelected(true);
                        dialog_item2.setSelected(false);
                        String userSex = "0";
                        HttpParams params = new HttpParams();
                        params.put("userSex", userSex);
                        OkGoUtils.progressRequest(MyUrl.editUserSex, PersonalDataActivity.this, params, new onNormalRequestListener() {
                            @Override
                            public void onSuccess(String body, int code) {
                                if (code == 0) {
                                    ToastUtils.showShort("设置成功");
                                    loadData();
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {

                            }
                        });
                        dialog.dismiss();
                    }
                }).show();
    }


    private static final int PHOTO_REQUEST_CAMERA = 1;
    private static final int PHOTO_REQUEST_GALLERY = 2;
    private static final int PHOTO_REQUEST_CUT = 3;
    private File tempFile;
    private File cropPhoto;
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private static final String PHOTO_FILE_NAME1 = "temp_photo1.jpg";


    private void saveImg() {
        if (cropPhoto == null) {
            ToastUtils.showShort("您还没有选择图片");
        } else {

            OkGoUtils.upLoadFile(MyUrl.editPhoto, this, null, "img", cropPhoto, new onUploadFileListener() {
                @Override
                public void onStart() {
                    LogUtils.e("开始上传");
                }

                @Override
                public void onUploadProgress(Progress progress) {

                }

                @Override
                public void onSuccess(String body, int code) {
                    if (code == 0) {
                        loadData();
                        ToastUtils.showShort("上传成功");
                        if (cropPhoto != null && cropPhoto.exists()) {
                            cropPhoto.delete();
                        }
                    }
                }

                @Override
                public void onError(Response<String> response) {
                    ToastUtils.showShort("上传失败，请重试");

                }

                @Override
                public void onFinish() {

                }
            });
        }
    }

    private void showDialog() {

        new RadishDialog.Builder(this).setView(R.layout.kingmall_dialog_selector_pic)
                .setText(R.id.dialog_title, "修改头像")
                .setClick(R.id.dialog_pic, new OnDialogViewClickListener() {
                    @Override
                    public void onClick(RadishDialog dialog, View view) {
                        dialog.dismiss();
                        mItem = 0;
                        // 这里item是根据选择的方式，
                        PermissionsUtils.getInstance().checkPermissions(PersonalDataActivity.this, new PermissionsUtils.IPermissionsResult() {
                            @Override
                            public void passPermissions() {
                                paizhao(0);
                            }

                            @Override
                            public void refusePermissions() {
                            }
                        }, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    }
                })
                .setClick(R.id.dialog_camera, new OnDialogViewClickListener() {
                    @Override
                    public void onClick(RadishDialog dialog, View view) {
                        dialog.dismiss();
                        mItem = 1;
                        // 这里item是根据选择的方式，
                        PermissionsUtils.getInstance().checkPermissions(PersonalDataActivity.this, new PermissionsUtils.IPermissionsResult() {
                            @Override
                            public void passPermissions() {
                                paizhao(1);
                            }

                            @Override
                            public void refusePermissions() {
                            }
                        }, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    }
                }).show();
    }


    private void paizhao(int item) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (item == 0) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent,
                        PHOTO_REQUEST_GALLERY);
            } else {
                StartTakePhoto();
            }
        } else {
            if (item == 0) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent,
                        PHOTO_REQUEST_GALLERY);
            } else {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    tempFile = new File(Environment
                            .getExternalStorageDirectory(),
                            PHOTO_FILE_NAME);
                    Uri uri = Uri.fromFile(tempFile);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    startActivityForResult(intent,
                            PHOTO_REQUEST_CAMERA);
                } else {
                    ToastUtils.showShort("未找到存储卡，无法存储照片！");
                }
            }

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults != null && grantResults.length != 0) {
            // 照相
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                    && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                paizhao(mItem);
            } else {
            }
        }
    }

    void StartTakePhoto() {
        tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
        CaptureFileUtils.startActionCapture(this, tempFile, PHOTO_REQUEST_CAMERA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PHOTO_REQUEST_GALLERY) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    crop(uri, 1);
                }
            } else {
                Log.e("radish", "图片NOT ");
            }

        } else if (requestCode == PHOTO_REQUEST_CAMERA) {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                if (tempFile != null && tempFile.exists()) {
                    LogUtils.e("tempFile.getPath()：" + tempFile.getPath());
                    crop(Uri.fromFile(tempFile), 0);
                }
            } else {
                Toast.makeText(this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == PHOTO_REQUEST_CUT) {
            try {
                final byte[] bytes = InputStream2ByteArray(cropPhoto.getAbsolutePath());
                if (bytes != null && bytes.length > 0) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Glide.with(getApplication()).load(bytes).apply(new RequestOptions().optionalTransform(new GlideCircleTransform())).into(ivIcon);
                            saveImg();
                            try {
                                if (tempFile != null && tempFile.exists()) {
                                    tempFile.delete();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, 200);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private byte[] InputStream2ByteArray(String filePath) throws IOException {
        InputStream in = new FileInputStream(filePath);
        byte[] data = toByteArray(in);
        in.close();

        return data;
    }

    private byte[] toByteArray(InputStream in) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }


    private void crop(Uri uri, int type) {
        Uri outputUri;

        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
        }

        if (type == 0) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".myFileProvider", tempFile);
            } else {
                uri = Uri.fromFile(tempFile);
            }
        }

        cropPhoto = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME1);
        if (cropPhoto.exists()) {
            cropPhoto.delete();
        }
        try {
            cropPhoto.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        outputUri = Uri.fromFile(cropPhoto);


        intent.setDataAndType(uri, "image/*");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        }
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);

        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        //输出的宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);

        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }
}
